from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings


def generate_access_token_openid(openid):
    """
    序列化openid
    :param openid: openid明文
    :return: openid密文
    """
    # 创建序列化器对象
    # s = Serializer('秘钥', '过期时间')
    s = Serializer(settings.SECRET_KEY, expires_in=600)
    # 序列化操作
    data = {'openid': openid}
    access_token_openid = s.dumps(data)
    # 返回openid密文
    return access_token_openid.decode()


def check_access_token_openid(access_token_openid):
    """
    反序列化openid
    :param access_token_openid: openid密文
    :return: openid明文
    """
    # 创建序列化器对象
    s = Serializer(settings.SECRET_KEY, expires_in=600)
    # 反序列化操作
    try:
        data = s.loads(access_token_openid)
    except BadData:
        # openid过期
        return None
    else:
        # 返回openid明文
        return data.get('openid')